package com.d3works.apps.base.web;

import com.d3works.app.AppSettings;
import com.d3works.apps.ReportFactory;
import com.d3works.apps.base.db.Company;
import com.d3works.apps.base.db.PrintingSettings;
import com.d3works.apps.base.report.IReport;
import com.d3works.apps.report.engine.ReportSettings;
import com.d3works.auth.AuthUtils;
import com.d3works.common.VersionUtils;
import com.d3works.exception.D3worksException;
import com.d3works.exception.db.TraceBack;
import com.d3works.meta.schema.actions.ActionView;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;
import java.math.BigDecimal;

public class TracebackController {

  public void printTraceback(ActionRequest request, ActionResponse response)
      throws D3worksException {
    TraceBack traceBack = request.getContext().asType(TraceBack.class);
    Long traceBackId = traceBack.getId();
    String name = "TraceBack " + traceBackId;
    Company activeCompany = AuthUtils.getUser().getActiveCompany();
    BigDecimal headerHeight = BigDecimal.ZERO;
    BigDecimal footerHeight = BigDecimal.ZERO;
    if (activeCompany != null) {
      PrintingSettings printingSettings = activeCompany.getPrintingSettings();
      headerHeight = printingSettings.getPdfHeaderHeight();
      footerHeight = printingSettings.getPdfFooterHeight();
    }
    String fileLink =
        ReportFactory.createReport(IReport.TRACEBACK, name + "-${date}")
            .addParam("Locale", ReportSettings.getPrintingLocale(null))
            .addParam("TracebackId", traceBackId)
            .addParam("SDKVersion", VersionUtils.getVersion().toString())
            .addParam("AOSVersion", AppSettings.get().get("application.version"))
            .addParam("HeaderHeight", headerHeight)
            .addParam("FooterHeight", footerHeight)
            .generate()
            .getFileLink();
    response.setView(ActionView.define(name).add("html", fileLink).map());
  }
}
